<?php
/*****************
*作者：jeff.liu
*联系方式：13810908686
*电子邮件：ljf1279@yeah.net
******************/
// 抓取远程资源文件
function get_remote_resource($url)
{
	$info = parse_url($url);//http://i3.sinaimg.cn/dy/temp/450/2008/0326/U2251P1T450D15F10119DT20081030093851.jpg
	$url = ereg_replace("[\\\"]",'',$url);
	$file_name = basename($info['path']);
	$arr_path = split("\.",$file_name);
	$file_ext = strtolower($arr_path[count($arr_path)-1]);
	if(!$file_ext)
	{
		$file_ext = 'jpg';
	}
	$content = file_get_contents($url);
	$save_path = '/spider/'.date('Y/m/d/');
	if(!@is_dir(IMG_ROOT.$save_path))
	{
		@mkdir(IMG_ROOT.$save_path,0777,true);// php5 only
	}
	$file_new_name = date('His').rand(100,999).'.'.$file_ext;
	if(file_put_contents(IMG_ROOT.$save_path.$file_new_name,$content))
	{
		return IMG_URL.$save_path.$file_new_name;
	}
	return false;
}
// 不丢失参数拼接分页页号
function get_page_no($pgnm,$pgno)
{
	$q = $_SERVER['QUERY_STRING'];
	parse_str($q,$qs);
	if($pgnm)
	{
	$qs[$pgnm] = $pgno;
	}
	return http_build_query($qs);
}

//发出提示
function alert($message = "", $action = "back", $location = "", $is_alert = true)
{
	global $time_start;
	$message .= '-----mysql:c'.$GLOBALS['db']->get_run_time().'|q'.$GLOBALS['db']->get_query_num().'&php:t'.(microtime(1) - $time_start) .'s';
	$path = dirname(__FILE__);
	$file_foot = $path."/foot.php";
	if($is_alert)
	{
		echo "$message <script>alert(\"$message\");</script>";
	}
	if($action == "location" && $location != '')
	{
		echo "<a href='$location' onclick='location.href=\"$location\";'>返回</a>";
		if($is_alert)
		{
			echo "<script>location.href='$location';</script>";
		}
		include($file_foot);
		exit;
	}
	if($action == "halt")
	{
		include($file_foot);
		exit;
	}
	if($action == "back")
	{
		echo "<a href='".$_SERVER['HTTP_REFERER']."' onclick='history.go(-1);'>返回</a>";
		if($is_alert)
		{
			echo "<script>history.go(-1);</script>";
		}
		include($file_foot);
		exit;
	}
}

function getTemplates($order = "")
{
	global $db;
	if($order)
		$order = " order by $order ";
	$sql = "select * from Template $order";
	$result = $db->query($sql);
	while($row = $db->fetch_array($result))
	{
		$arrReturn[] = new Template($row);
	}
	return $arrReturn;
}

function sub_str($str, $length = 0, $append=true)
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)
    {
        return $str;
    }
    elseif ($length < 0)
    {
        $length = $strlength + $length;
        if ($length < 0)
        {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'UTF-8');
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'UTF-8');
    }
    else
    {
        $newstr = trim_right(substr($str, 0, $length));
    }

    if ($append && $str != $newstr)
    {
        $newstr .= '...';
    }

    return $newstr;
}

function trim_right($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;

    if ($length > 0)
    {
        $str = substr($str, 0, 0 - $length);
    }

    return $str;
}

	// 上传文件，根据指定的文件类型和大小存放在指定的路径中；返回存储的文件名
	function uploadFile($formEl, $saveDir, $allowType, $allowSize)
	{
		$file = $_FILES[$formEl]["tmp_name"];
		$file_name = $_FILES[$formEl]["name"];
		$file_type = $_FILES[$formEl]["type"];
		$file_size = $_FILES[$formEl]["size"];

		if (!$file || $file == "none")
			return "";

		$timeNow = date('U');
		if ($file_type == "image/gif")
			$fileExt = ".gif";
		elseif ($file_type == "image/png")
			$fileExt = ".png";
		elseif ($file_type == "image/jpg" || $file_type == "image/jpeg" || $file_type == "image/pjpeg")
			$fileExt = ".jpg";
		elseif ($file_type == "image/bmp")
			$fileExt = ".bmp";
		else
		{
			$fileExt1 = explode(".", $file_name);
			if (is_array($fileExt1) && count($fileExt1) > 1)
				$fileExt = ".".$fileExt1[count($fileExt1) - 1];
		}
		
		if ($allowType && !strstr($allowType, $fileExt))
		{
			$error = true;
			$errorMessage = "上传的文件格式不正确！请上传 $allowType 格式的文件！";
		}
		
		if (!$error	&& $file_size > 3072000)	// 判断文件大小
		{
			$error = true;
			$errorMessage = "请不要上传大于2M的文件！";
		}
		
		if (!$error)
		{
			$tempDir = $saveDir;
			if (!is_dir($tempDir))
				MakeDir($tempDir);
			
			$destFile = $tempDir."/U".$_SESSION["AID"]."D".date('U').'R'.rand(100,999).$fileExt;
			copy($file, $destFile);
			unlink($file);

			return str_replace($tempDir."/", "", $destFile);
		}
		else
			return "error: $errorMessage";
	}
	//递归建立文件夹
	function MakeDir($DirName)
	{
		$dir = split('[\/\\]',$DirName);
		if(!@mkdir($DirName,0777,true))
		{
			$strDir = "";
			for($i = 0; $i < count($dir); $i++)
			{
				$strDir .= $dir[$i]."/";
				if($strDir != "/")
				{
					if(!is_dir($strDir))
						@mkdir($strDir,0777);
				}
			}
		}
	}

	function strInList($str,$strList)
	{
		$list = explode(",",$strList);
		for($i=0;$i<count($list);$i++)
		{
			if($str == $list[$i])
				return true;
		}
		return false;
	}

	function unzip($file, $savePath)
	{
		
	}
	//$filepath:文件存入其他表的路径 $realpath:文件在服务器上的绝对路径 $info:文件信息，格式(数据库名:表名:主键值)
	function insertFileInfo($filepath, $realpath, $info)
	{
		
	}

	function checkAdmin()
	{
		
	}
	function strInArray($str, $arr)
	{
		if(!is_array($arr))
			return $str == $arr;
		foreach($arr as $val)
		{
			if(strInArray($str, $val))
				return true;
		}
		return false;
	}
	function execSql($sql)
	{
		if(eregi("^zoshow_sql=",$sql))
		{
			$sql = str_replace("zoshow_sql=","",$sql);
			$db = $GLOBALS['zoshow_db'];
		}
		else
		{
			$db = $GLOBALS['db'];
		}
		$arrReturn = array();
		if($result = $db->query($sql))
		{
			while ($row = $db->fetch_array($result))
			{
				$arrReturn[] = $row;
			}
		}
		return $arrReturn;
	}
	// 需要GD支持
	function zoomImage($img_src,$width=0,$height=0,$prefix='', $quality = 0)
	{
		$img_path = IMG_ROOT.'/'.$img_src;
		if($width<=0 && $height<=0)
		{
			return false;
		}
		if(!$img_src)
		{
			return false;
		}
		if(!is_file($img_path))
		{
			return false;
		}
		//
		$gd_ver = gd_version();
		 
		if ($gd_ver == 0)
		{
			return false;
		}
		$surfix = '';
		// 后缀
		if($width > 0)
		{
			$surfix .= '_w'.$width;
		}
		if($height > 0)
		{
			$surfix .= '_h'.$height;
		}

		$org_info = @getimagesize($img_path);
		$img_org = img_resource($img_path, $org_info[2]);
		/* 原始图片以及缩略图的尺寸比例 */
		$scale_org      = $org_info[0] / $org_info[1];
		/* 处理只有缩略图宽和高有一个为0的情况，这时背景和缩略图一样大 */
		if ($width <= 0)
		{
			$width = ceil($height * $scale_org);
		}
		if ($height <= 0)
		{
			$height = ceil($width / $scale_org);
		}
		/* 创建缩略图的标志符 */
		if ($gd_ver == 2)
		{
			$img_thumb  = imagecreatetruecolor($width, $height);
		}
		else
		{
			$img_thumb  = imagecreate($width, $height);
		}
		// 背景处理
		sscanf('ffffff', "%2x%2x%2x", $red, $green, $blue);
		$clr = imagecolorallocate($img_thumb, $red, $green, $blue);
		imagefilledrectangle($img_thumb, 0, 0, $width, $height, $clr);

		/* 将原始图片进行缩放处理 */
		if ($gd_ver == 2)
		{
			imagecopyresampled($img_thumb, $img_org, 0, 0, 0, 0, $width, $height, $org_info[0], $org_info[1]);
		}
		else
		{
			imagecopyresized($img_thumb, $img_org, 0, 0, 0, 0, $width, $height, $org_info[0], $org_info[1]);
		}
		$img_dest_name = explode('.',$img_src);
		$img_dest_name = $img_dest_name[0].$surfix.'.jpg';
		if($quality > 0 && $quality != 75)
		{
			imagejpeg($img_thumb,IMG_ROOT.'/'.$img_dest_name, $quality);
		}
		else
		{
			imagejpeg($img_thumb,IMG_ROOT.'/'.$img_dest_name);
		}
		return $img_dest_name;
	}
	function gd_version()
	{
		static $version = -1;

		if ($version >= 0)
		{
			return $version;
		}

		if (!extension_loaded('gd'))
		{
			$version = 0;
		}
		else
		{
			// 尝试使用gd_info函数
			if (PHP_VERSION >= '4.3')
			{
				if (function_exists('gd_info'))
				{
					$ver_info = gd_info();
					preg_match('/\d/', $ver_info['GD Version'], $match);
					$version = $match[0];
				}
				else
				{
					if (function_exists('imagecreatetruecolor'))
					{
						$version = 2;
					}
					elseif (function_exists('imagecreate'))
					{
						$version = 1;
					}
				}
			}
			else
			{
				if (preg_match('/phpinfo/', ini_get('disable_functions')))
				{
					/* 如果phpinfo被禁用，无法确定gd版本 */
					$version = 1;
				}
				else
				{
					// 使用phpinfo函数
					ob_start();
					phpinfo(8);
					$info = ob_get_contents();
					ob_end_clean();
					$info = stristr($info, 'gd version');
					preg_match('/\d/', $info, $match);
					$version = $match[0];
				}
			}
		}

		return $version;
	}
	// 
	function img_resource($img_file, $mime_type)
	{
		switch ($mime_type)
		{
			case 1:
			case 'image/gif':
				$res = imagecreatefromgif($img_file);
				break;

			case 2:
			case 'image/pjpeg':
			case 'image/jpeg':
				$res = imagecreatefromjpeg($img_file);
				break;

			case 3:
			case 'image/x-png':
			case 'image/png':
				$res = imagecreatefrompng($img_file);
				break;

			default:
				return false;
		}

		return $res;
	}
	if(!function_exists("addslashes_deep"))
	{
		function addslashes_deep($value)
		{
			if (empty($value))
			{
				return $value;
			}
			elseif (is_object($value))
			{
				foreach ($value as $k=>$a)
				{
					$value->$k = addslashes_deep($a);
				}
				return $value;
			}
			else
			{
				return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
			}
		}
	}
	?>
